package com.yellow.web.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yellow.constant.MessageConstant;
import com.yellow.constant.RedisConstant;
import com.yellow.enity.PageResult;
import com.yellow.enity.QueryPageBean;
import com.yellow.enity.Result;
import com.yellow.pojo.Setmeal;
import com.yellow.service.SetMealService;
import com.yellow.utils.AliyunOSSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.util.*;

@RestController
@RequestMapping("/setmeal")
public class SetMealController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private SetMealService setMealService;

    @RequestMapping("/add")
    public Result add(int[] checkgroupIds, @RequestBody Setmeal setmeal) {
        try {
            setMealService.add(setmeal, checkgroupIds);
            return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_SETMEAL_FAIL);
        }

    }

    @RequestMapping("/PageQuery")
    public PageResult PageQuery(@RequestBody QueryPageBean queryPageBean) {
        try {
            PageResult pageQuery = setMealService.PageQuery(queryPageBean);
            return pageQuery;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile) {
        try {
            //获取文件名称
            String fileName = imgFile.getOriginalFilename();
            //获得文件的后缀
            int index = fileName.lastIndexOf('.') - 1;
            String suffix = fileName.substring(index);
            String uuid = UUID.randomUUID().toString();
            String fileName_upload = uuid + suffix;
            Map<String, String> map = new HashMap<>();

            //使用阿里云上传图片
            String url = AliyunOSSUtils.upload2AliyunOOS(imgFile.getBytes(), fileName_upload);
            //存储在redis中
            map.put("url", url);
            map.put("filename", fileName_upload);
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES, fileName_upload);
            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }

    }
}
